"""
员工管理接口
作者：资深Flask讲师
功能：员工列表、员工详情、员工编辑、员工禁用等
权限：超级管理员可操作所有员工，部门经理只能操作本部门员工，普通员工只能查看自己
"""

from flask import Blueprint, jsonify, request
from myflask.tools.bd import db
from myflask.models.user import User
from myflask.tools.auth import require_role, require_same_user_or_manager, check_department_permission

employee_blue = Blueprint('employee_blue', __name__)


@employee_blue.route('/list', methods=['GET'])
@require_role('admin', 'manager')
def employee_list():
    """
    获取员工列表
    权限：超级管理员可查看所有员工，部门经理只能查看本部门员工
    参数：department_id（可选，筛选部门）
    """
    try:
        user_info = getattr(request, 'user_info', None)
        department_id = request.args.get('department_id', type=int)
        
        # 构建查询
        query = User.query
        
        # 超级管理员可查看所有员工
        if user_info.get('role') == 'admin':
            if department_id:
                query = query.filter_by(department_id=department_id)
        # 部门经理只能查看本部门员工
        elif user_info.get('role') == 'manager':
            query = query.filter_by(department_id=user_info.get('department_id'))
        
        # 排除超级管理员（一般不显示在员工列表中）
        query = query.filter(User.role != 'admin')
        
        employees = query.order_by(User.created_at.desc()).all()
        
        return jsonify({
            "code": 200,
            "message": "获取员工列表成功",
            "data": {
                "employees": [emp.to_dict() for emp in employees],
                "total": len(employees)
            }
        })
        
    except Exception as e:
        return jsonify({
            "code": 500,
            "message": f"获取员工列表失败: {str(e)}"
        }), 500


@employee_blue.route('/detail/<int:user_id>', methods=['GET'])
def employee_detail(user_id):
    """
    获取员工详情
    权限：超级管理员可查看所有员工，部门经理可查看本部门员工，普通员工只能查看自己
    """
    try:
        user_info = getattr(request, 'user_info', None)
        
        # 查询员工
        employee = User.query.get(user_id)
        
        if not employee:
            return jsonify({
                "code": 404,
                "message": "员工不存在"
            }), 404
        
        # 权限检查
        if user_info.get('role') == 'admin':
            # 超级管理员可查看所有员工
            pass
        elif user_info.get('role') == 'manager':
            # 部门经理只能查看本部门员工
            if employee.department_id != user_info.get('department_id'):
                return jsonify({
                    "code": 403,
                    "message": "权限不足：只能查看本部门员工"
                }), 403
        else:
            # 普通员工只能查看自己
            if employee.id != user_info.get('user_id'):
                return jsonify({
                    "code": 403,
                    "message": "权限不足：只能查看自己的信息"
                }), 403
        
        return jsonify({
            "code": 200,
            "message": "获取员工详情成功",
            "data": employee.to_dict()
        })
        
    except Exception as e:
        return jsonify({
            "code": 500,
            "message": f"获取员工详情失败: {str(e)}"
        }), 500


@employee_blue.route('/update/<int:user_id>', methods=['PUT'])
def employee_update(user_id):
    """
    更新员工信息
    权限：超级管理员可更新所有员工，部门经理可更新本部门员工，普通员工只能更新自己
    请求体：{"real_name": "张三", "email": "zhangsan@example.com", "phone": "13800138000"}
    """
    try:
        user_info = getattr(request, 'user_info', None)
        data = request.get_json()
        
        if not data:
            return jsonify({
                "code": 400,
                "message": "请求数据格式错误"
            }), 400
        
        # 查询员工
        employee = User.query.get(user_id)
        
        if not employee:
            return jsonify({
                "code": 404,
                "message": "员工不存在"
            }), 404
        
        # 权限检查
        if user_info.get('role') == 'admin':
            # 超级管理员可更新所有员工
            pass
        elif user_info.get('role') == 'manager':
            # 部门经理只能更新本部门员工
            if employee.department_id != user_info.get('department_id'):
                return jsonify({
                    "code": 403,
                    "message": "权限不足：只能更新本部门员工"
                }), 403
        else:
            # 普通员工只能更新自己
            if employee.id != user_info.get('user_id'):
                return jsonify({
                    "code": 403,
                    "message": "权限不足：只能更新自己的信息"
                }), 403
        
        # 更新字段
        if 'real_name' in data:
            employee.real_name = data['real_name']
        if 'email' in data:
            employee.email = data['email']
        if 'phone' in data:
            employee.phone = data['phone']
        
        # 只有管理员和部门经理可以更改部门和角色
        if user_info.get('role') in ['admin', 'manager']:
            if 'department_id' in data:
                employee.department_id = data['department_id']
            # 只有超级管理员可以更改角色
            if user_info.get('role') == 'admin' and 'role' in data:
                employee.role = data['role']
        
        db.session.commit()
        
        return jsonify({
            "code": 200,
            "message": "更新员工信息成功",
            "data": employee.to_dict()
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            "code": 500,
            "message": f"更新员工信息失败: {str(e)}"
        }), 500


@employee_blue.route('/status/<int:user_id>', methods=['PUT'])
@require_role('admin', 'manager')
def employee_status(user_id):
    """
    启用/禁用员工
    权限：超级管理员可操作所有员工，部门经理只能操作本部门员工
    请求体：{"status": 0}  # 0-禁用，1-启用
    """
    try:
        user_info = getattr(request, 'user_info', None)
        data = request.get_json()
        
        if not data or 'status' not in data:
            return jsonify({
                "code": 400,
                "message": "请提供status参数"
            }), 400
        
        # 查询员工
        employee = User.query.get(user_id)
        
        if not employee:
            return jsonify({
                "code": 404,
                "message": "员工不存在"
            }), 404
        
        # 权限检查
        if user_info.get('role') == 'manager':
            # 部门经理只能操作本部门员工
            if employee.department_id != user_info.get('department_id'):
                return jsonify({
                    "code": 403,
                    "message": "权限不足：只能操作本部门员工"
                }), 403
        
        # 不能禁用超级管理员
        if employee.role == 'admin':
            return jsonify({
                "code": 403,
                "message": "不能禁用超级管理员"
            }), 403
        
        # 更新状态
        employee.status = data['status']
        db.session.commit()
        
        status_text = "启用" if data['status'] == 1 else "禁用"
        
        return jsonify({
            "code": 200,
            "message": f"{status_text}员工成功",
            "data": employee.to_dict()
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            "code": 500,
            "message": f"操作失败: {str(e)}"
        }), 500


@employee_blue.route('/create', methods=['POST'])
@require_role('admin', 'manager')
def employee_create():
    """
    创建员工
    权限：超级管理员可创建任何部门的员工，部门经理只能创建本部门员工
    请求体：{"user": "zhangsan", "password": "123456", "real_name": "张三", "department_id": 1, "role": "employee"}
    """
    try:
        user_info = getattr(request, 'user_info', None)
        data = request.get_json()
        
        if not data:
            return jsonify({
                "code": 400,
                "message": "请求数据格式错误"
            }), 400
        
        user = data.get('user', '').strip()
        password = data.get('password', '').strip()
        real_name = data.get('real_name', '').strip()
        email = data.get('email', '').strip()
        phone = data.get('phone', '').strip()
        department_id = data.get('department_id')
        role = data.get('role', 'employee')
        
        # 数据验证
        if not user or not password:
            return jsonify({
                "code": 400,
                "message": "用户名和密码不能为空"
            }), 400
        
        # 检查用户名是否已存在
        existing_user = User.query.filter_by(user=user).first()
        if existing_user:
            return jsonify({
                "code": 400,
                "message": "用户名已存在"
            }), 400
        
        # 权限检查：部门经理只能创建本部门员工
        if user_info.get('role') == 'manager':
            if department_id != user_info.get('department_id'):
                return jsonify({
                    "code": 403,
                    "message": "权限不足：只能创建本部门员工"
                }), 403
            # 部门经理不能创建管理员
            if role == 'admin':
                return jsonify({
                    "code": 403,
                    "message": "权限不足：不能创建管理员"
                }), 403
        
        # 创建新员工
        new_employee = User(
            user=user,
            real_name=real_name if real_name else None,
            email=email if email else None,
            phone=phone if phone else None,
            department_id=department_id,
            role=role,
            status=1
        )
        new_employee.set_password(password)
        
        db.session.add(new_employee)
        db.session.commit()
        
        return jsonify({
            "code": 200,
            "message": "创建员工成功",
            "data": new_employee.to_dict()
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({
            "code": 500,
            "message": f"创建员工失败: {str(e)}"
        }), 500

